﻿namespace EyeOpen.TimeAssistant.UI.Silverlight
{
    using System.Windows;
    using System.Windows.Controls;
    using Microsoft.Practices.Composite.Modularity;
    using Microsoft.Practices.Composite.UnityExtensions;
    using Microsoft.Practices.ServiceLocation;
    using Microsoft.Practices.Unity;

    public class Bootstrapper : UnityBootstrapper
    {
        /// <summary>
        /// Gets or sets the container.
        /// </summary>
        /// <value>The container.</value>
        public IUnityContainer TheContainer
        {
            get;
            set;
        }

        /// <summary>
        /// Creates the shell.
        /// </summary>
        /// <returns></returns>
        protected override DependencyObject CreateShell()
        {
            return Application.Current.RootVisual = new Shell();
        }

        /// <summary>
        /// Initializes the modules.
        /// </summary>
        protected override void InitializeModules()
        {
            // get the IoC container
            TheContainer = ServiceLocator.Current.GetInstance<IUnityContainer>();

            // Get a reference to the shell. Usually you do this in a Module
            var shell = Application.Current.RootVisual as Shell;

            // Create Views and ViewModels
            AddToContainer(shell, "content", new MainPage());

            // Register the service
            TheContainer.RegisterInstance(
                typeof(DialogManager),
                new DialogManager(),
                new ContainerControlledLifetimeManager());

            base.InitializeModules();
        }

        /// <summary>
        /// Gets the module catalog.
        /// </summary>
        /// <returns></returns>
        protected override IModuleCatalog GetModuleCatalog()
        {
            return new ModuleCatalog();
        }

        /// <summary>
        /// Adds to container.
        /// </summary>
        /// <param name="shell">The shell.</param>
        /// <param name="name">The name.</param>
        /// <param name="view"></param>
        private static void AddToContainer(Shell shell, string name, UserControl view)
        {
            var contentControl = shell.FindName(name) as ContentControl;

            if (contentControl != null)
            {
                contentControl.Content = view;
            }
        }
    }
}
